package com.jd.tuning.jvm.lock.reen;


import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试公平、非公平
 */
public class ReentrantLockTest2 {


    public static void main(String[] args) throws InterruptedException {
            FairTest test=new FairTest();
            Thread t1=new Thread(test);
            Thread t2=new Thread(test);
            Thread t3=new Thread(test);
            t1.start();
            t2.start();
            t3.start();

    }
}

class  FairTest implements  Runnable{
    //默认创建的是非公平锁
    //synchronized 只能创建非公平锁
    //非公平锁，运行插队，一般来说，非公平锁的性能要比公平锁的性能要高
    private ReentrantLock lock=new ReentrantLock(true);
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"开始运行");
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"拿到了锁");
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("sleep 发生异常");
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unlock();
        }
    }
}
